package me.kennylee.mobile.sms.check;

import com.google.common.collect.Lists;
import me.kennylee.cache.CacheHelper;
import me.kennylee.mobile.sms.cache.SmsCodeCacheKey;
import me.kennylee.mobile.sms.code.SmsResponse;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p> 验证码校验器 </p>
 * <p>Created on 2/2/2018.</p>
 *
 * @author kennylee
 */
public class VerifyCodeValidator {

    private static List<CodeValidator> validators = Collections.unmodifiableList(Lists.newArrayList());

    static {
        addValidator((phone, code) -> StringUtils.equals(CacheHelper.get(SmsCodeCacheKey.getSmsCodeLive(), phone, String.class), code) ?
                SmsResponse.success() : SmsResponse.error());
    }

    public static SmsResponse check(String mobile, String code) {
        if (validators.isEmpty()) {
            return SmsResponse.success();
        } else {
            SmsResponse response = null;
            for (CodeValidator validator : validators) {
                response = validator.check(mobile, code);
                if (!response.isSuccess()) {
                    break;
                }
            }
            return response;
        }
    }

    public static void addValidator(CodeValidator validator) {
        List<CodeValidator> l = Lists.newArrayList(validators);
        l.add(validator);
        validators = Collections.unmodifiableList(l);
    }

}
